package com.CatTalkApi.DAO;

import java.sql.*;

//数据库操作单例模式，用来进行一些数据库有关的操作
public class DataBaseContext {
    private static DataBaseContext Instance = null;
    private Connection conn;
    private Statement stmt;

    public static DataBaseContext getInstance() {//static将变量放在静态区，这样进行全局调用
        if (DataBaseContext.Instance == null) {
            DataBaseContext.Instance = new DataBaseContext();
        }
        return DataBaseContext.Instance;
    }

    private void Init() throws Exception { //初始化数据库的连接
        Class.forName("com.mysql.cj.jdbc.Driver");
        String url = "jdbc:mysql://127.0.0.1:3306/CatWebDatabase?useSSL=false&allowPublicKeyRetrieval=true";
        String usrName = "root";
        String usrPwd = "123456";
        conn = DriverManager.getConnection(url, usrName, usrPwd);
    }

    public ResultSet DoSQLQuery(String sql) {
        try {
            return stmt.executeQuery(sql);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    public Statement GetStmt() {
        try { // 尝试获得连接
            this.Close();
            DataBaseContext.Instance.Init();
            stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
            return this.stmt;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void Close() {
        try {
            if (stmt != null) {
                stmt.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
